<?php 
function print_menu2($menu, $index = 0) {
	$hyphen = '';
	for($i = 0; $i < $index; $i++)
		$hyphen .= '- ';
	echo '<option value="'.$menu->term_id.'">' . $hyphen . $menu->term_name.'</option>';

	if (!empty($menu->child)) {
		$index++;
		foreach ($menu->child as $item) print_menu2($item, $index);
	}
}
?>
<div class="panel panel-default" id="popup_add_posts">
	<div class="panel-heading"><?php echo $title; ?></div>
	<div class="panel-body">
        <!-- Nav tabs -->
        <ul class="nav nav-tabs">
           <li class="active"><a href="#list" data-toggle="tab">Danh sách tin</a></li>
           <li><a href="#addnew" data-toggle="tab">Thêm tin</a></li>
       </ul>
       <!-- Tab panes -->
       <div class="tab-content">
           <div id="list" class="tab-pane fade in active">
              <form method="POST" name="list" action="" class="form-horizontal">
                <div class="">
                   <table id="tab1" class="table table-striped table-bordered table-hover">
                      <thead>
                         <tr>
                            <th>Tiêu đề</th>
                            <th>Chuyên mục</th>
                            <th class="check-all">
                                <div data-toggle="tooltip" data-title="Check All" class="checkbox c-checkbox">
                                 <label>
                                  <input type="checkbox">
                                  <span class="fa fa-check"></span>
                              </label>
                          </div>
                      </th>
                  </tr>
              </thead>
          </table>
      </div>
  </form>
  <div class="clearfix margin-top10 margin-bottom10">	          		
   <button type="button" class="btn btn-labeled btn-success" data-updateList="true">
      <span class="btn-label"><i class="fa fa-check"></i> Cập nhật danh sách</span>
  </button>
  <button type="button" class="btn btn-labeled btn-danger" data-removePost="true">
      <span class="btn-label"><i class="fa fa-trash-o"></i> Xóa các nội dung được đánh dấu</span>
  </button>
</div>
</div>
<div id="addnew" class="tab-pane fade">
    <div class="well">
       <form role="form" class="form-inline">
           <div class="form-group">
              <div class="input-group m-b">
                  <span class="input-group-addon">Chuyên mục</span>
                  <select name="cat_id" id="input-type" class="form-control m-b">
                     <option value="0">Tất cả</option>
                     <?php if (isset($menu_tree) && $menu_tree) foreach ($menu_tree as $menu) print_menu2($menu); ?>
                 </select>
             </div>
         </div>
         <div class="form-group">
          <label for="input-search" class="sr-only">Search</label>
          <input name="keyword" id="input-search" type="text" placeholder="Type your keyword" class="form-control">
      </div>
      <div class="form-group">
          <div class="input-group m-b">
              <select name="type" id="input-type" class="form-control m-b">
                 <option value="0">Tất cả</option>
                 <option value="1">Tiêu đề</option>
                 <option value="2">Tác giả</option>
             </select>
             <span id="searchBtn" class="btn input-group-addon"><i class="fa fa-search"></i></span>
         </div>
     </div>
 </form>
</div>

<div class="clearfix margin-top10 margin-bottom10">
   <button type="button" class="btn btn-labeled btn-info addnewposts">
      <span class="btn-label"><i class="fa fa-check"></i> Chọn các tin được đánh dấu</span>
  </button>
</div>

<form method="POST" name="addnew" action="" class="form-horizontal">
    <div class="">
       <table id="listposts" class="table table-striped table-bordered table-hover">
          <thead>
             <tr>
                <th>Tiêu đề</th>
                <th>Chuyên mục</th>
                <th>Đăng lúc</th>
                <th>Lượt xem</th>
                <th class="check-all">
                    <div data-toggle="tooltip" data-title="Check All" class="checkbox c-checkbox">
                     <label>
                      <input type="checkbox">
                      <span class="fa fa-check"></span>
                  </label>
              </div>
          </th>
      </tr>
  </thead>
</table>
</div>
</form>

<div class="clearfix margin-top10 margin-bottom10">
   <button type="button" class="btn btn-labeled btn-info addnewposts">
      <span class="btn-label"><i class="fa fa-check"></i> Chọn các tin được đánh dấu</span>
  </button>
</div>
</div>
</div>
</div>
</div>
<!-- END panel-->

<script type="text/javascript">
    (function($, window, document){
      'use strict';

      var Selector = 'th.check-all';
      var parent_element = "<?php echo $meta_key ?>";
      function update_data(datatable)
      {

        $("#"+parent_element).html("");
        datatable
        .column( 0 )
        .data()
        .each( function ( value, index ) {
           // console.log( 'Data in index: '+index+' is: '+value );
            $("#"+parent_element).append("<li>"+value+"</li>");
        } );
    }

    $(Selector).on('change', function() {
       var $this = $(this),
       index= $this.index() + 1,
       checkbox = $this.find('input[type="checkbox"]'),
       table = $this.parents('table');
	    // Make sure to affect only the correct checkbox column
	    table.find('tbody > tr > td:nth-child('+index+') input[type="checkbox"]').prop('checked', checkbox[0].checked);
 });

    $(".addnewposts").click(function(){
  		//console.log($("form[name=addnew]").serialize());
  		$.ajax({
            type: "POST",
            url: "<?php echo $this->url_index; ?>/ajax_add_posts/<?php echo $post_id ?>/<?php echo $meta_key ?>",
            data: $("form[name=addnew]").serialize(),
            async: false,
            success: function(res) {
                res = $.parseJSON(res);
                //console.log(res);
                if(res.status == false)
                	$.notify("Cập nhật thất bại!", 'success');
                else
                	$.notify("Cập nhật thành công!", 'success');
                $('#tab1').DataTable().ajax.reload();
                update_data($('#tab1').DataTable());
            }       
        });
  	});

    $(document).on('click', '[data-updateList="true"]', function(){
        var tab1 = $('#tab1').DataTable();
        tab1.ajax.reload();
        update_data(tab1);
        
    });

    $(document).on('click', '#searchBtn', function(){
        $('#listposts').DataTable().ajax.reload();
    });

    $(document).on('click', '[data-removePost="true"]', function() {
  		//deleterows();
  		var tab1 = $('#tab1').DataTable();
  		$.ajax({
            type: "POST",
            url: "<?php echo admin_url();?>posts/ajax_del_meta_post/<?php echo $post_id ?>/<?php echo $meta_key ?>",
            data: tab1.$('input:checked').serialize(),
            async: false,
            success: function(res) {
                res = $.parseJSON(res);
                console.log(res);
                if(res.status == false)
                	$.notify("Cập nhật thất bại!", 'success');
                else
                	$.notify("Cập nhật thành công!", 'success');
                $('#tab1').DataTable().ajax.reload();
                update_data($('#tab1').DataTable());
            }       
        });
  	});

}(jQuery, window, document));
</script>


<script type="text/javascript">
    $(document).ready(function() {

        var tab1 = $('#tab1').dataTable( {
          dom: '<"top"l>rt<"bottom"pi>',
          processing: true,
          serverSide: true,
          ajax: {
            "url": "<?php echo admin_url().'posts/ajax_get_meta_post/'.$post_id.'/'.$meta_key; ?>",
            "type": "GET",
            data: function(d) {
                    //d.cat_id = $('#daterange').val();
                    //d.agency = $('[data-loadCliens="true"]').val();
                },
                async: false/*,
                success: function(response) {
                    console.log(response);
                }*/
            },
            language: {
                url: "<?php echo admin_theme_url();?>js/Vietnamese.json"
            },
            columns: [
            { 
                "data": 'post_title',
                "orderable": true
            },
            { 
                "data": 'post_category',
                "orderable": true
            },
            { 
                "class": "text-center",
                "data": 'post_id',
                "orderable": false,
                "render": function ( data, type, full, meta ) {
                	var str = "";
                	str += '<div class="checkbox c-checkbox">';
                    str += ' 	<label>';
                    str += '    	<input type="checkbox" name="post_id[]" value="'+data+'">';
                    str += '    	<span class="fa fa-check"></span>';
                    str += ' 	</label>';
                    str += '</div>';
                    return str;
                }
            }
            ]
        } );

var tab1 = $('#tab1').DataTable();

$('#listposts tfoot th').each( function () {
  var th = $('#listposts thead th').eq( $(this).index() );
  var type = th.attr('type');
  if(type === undefined) {
     var title = th.text();
     $(this).html( '<input type="text" class="form-control" placeholder="Search '+title+'" style="max-width: 100%;width: 100%;" />' );
 }
} );

var dttable = $('#listposts').dataTable( {
  dom: '<"top"fl>rt<"bottom"pi><"clear">',
  processing: true,
  serverSide: true,
  ajax: {
    "url": "<?php echo admin_url().'posts/ajax_datatable'; ?>",
    "type": "GET",
    data: function(d) {
        d.cat_id = $('select[name=cat_id]').val();
        d.keyword = $('input[name=keyword]').val();
    },
            async: false/*,
            success: function(response) {
                console.log(response);
            }*/
        },
        language: {
            url: "<?php echo admin_theme_url();?>js/Vietnamese.json"
        },
        columns: [
        { 
            "data": 'post_title',
            "orderable": true
        },
        { 
            "data": 'post_category',
            "orderable": true
        },
        { 
            "data": 'date_create',
            "orderable": true
        },
        { 
            "data": 'post_views',
            "orderable": true
        },
        { 
            "class": "text-center",
            "data": 'post_id',
            "orderable": false,
            "render": function ( data, type, full, meta ) {
               var str = "";
               str += '<div class="checkbox c-checkbox">';
               str += ' 	<label>';
               str += '    	<input type="checkbox" name="post_id[]" value="'+data+'">';
               str += '    	<span class="fa fa-check"></span>';
               str += ' 	</label>';
               str += '</div>';
               return str;
           }
       }
       ]
   } );

var dttable = $('#listposts').DataTable();
	/*
	dttable.columns().eq( 0 ).each( function ( colIdx ) {
		var th = $('#listposts tfoot th').eq( colIdx );
        $( 'input[type=text]', th ).on( 'keyup change', function () {
            dttable
                .column( colIdx )
                .search( this.value )
                .draw();
        } );
    } );
*/
});
</script>

<style>
	.table>caption+thead>tr:first-child>td, .table>caption+thead>tr:first-child>th, .table>colgroup+thead>tr:first-child>td, .table>colgroup+thead>tr:first-child>th, .table>thead:first-child>tr:first-child>td, .table>thead:first-child>tr:first-child>th {
        border: 1px solid #ddd;
    }
    .form-inline th .checkbox input[type=checkbox], .form-inline th .radio input[type=radio] {
      position: absolute;
  }
</style>